//
//  ZDRefreshControl.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/11/3.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class ZDRefreshControl: UIRefreshControl {

    //MRAK: - 构造函数
    override init() {
        
        super.init()
        
        //隐藏系统菊花
        tintColor = UIColor.clearColor()
        
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 准备UI
    private func prepareUI() {
        
        //添加子控件
        addSubview(refreshView)
        
        //添加约束
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    //定义标志 记录箭头旋转后的状态
    var upFlag: Bool = false
    
    //MARK: - 覆盖父类的frame属性 监听frame改变  
    //y = refreshControl的左上角 相对于 tableView的左上角的偏移值
    override var frame: CGRect {
        
        didSet {
        
            let offsetY = frame.origin.y
            let refOffsetMax: CGFloat = -60
            
            //如果往上滚动 直接返回
            if offsetY >= 0 {
            
                return
            }
            
//            print(frame)
            
            //通过判断系统的控件是否在刷新来决定
            if refreshing {
            
                //开始刷新
                self.refreshView.startRefresh()
            }
            
            
            if offsetY < refOffsetMax && !upFlag {
            
                print("箭头向上")
                
                //修改标志
                upFlag = true

                self.refreshView.rotationAnima(upFlag)
           
            }else if offsetY > refOffsetMax && upFlag {
            
                print("箭头向下")
                
                //修改标志
                upFlag = false
                
                self.refreshView.rotationAnima(upFlag)
            }
        }
    }
    
    //MARK: - 重写父类的endRefreshing方法
    override func endRefreshing() {
        
        super.endRefreshing()
        
        refreshView.stopRefresh()
    }
    
    
    //MARK: - 懒加载
    lazy var refreshView: ZDRefreshView = ZDRefreshView.refreshView()
    
}
